<script setup lang="ts">
import { RouterView, useRouter, useRoute } from 'vue-router'
import { computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import type { UserVO } from '@/api/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 是否在登录或注册页
const isAuthPage = computed(() => {
  return route.name === 'login' || route.name === 'register'
})

// 扩展用户信息类型，添加avatar属性
interface UserDisplay extends Partial<UserVO> {
  username: string
  email: string
  phone: string
  role: string
  studentNumber: string
  avatar: string
}

// 用户信息
const userInfo = computed<UserDisplay>(() => {
  if (userStore.userInfo) {
    return {
      ...userStore.userInfo,
      avatar: '', // API没有返回头像，使用默认空值
    }
  }

  return {
    username: '用户',
    email: '',
    phone: '',
    role: '',
    studentNumber: '',
    avatar: '',
  }
})

// 角色映射
const roleMap: Record<string, string> = {
  STUDENT: '学生',
  TEACHER: '教师',
  ADMIN: '管理员',
}

// 初始化用户信息
const initUserInfo = async () => {
  if (localStorage.getItem('userInfo') && !userStore.isLoggedIn) {
    try {
      await userStore.init()
    } catch (error) {
      console.error('Error al inicializar la información del usuario:', error)
    }
  }
}

// 处理下拉菜单命令
const handleCommand = (command: string) => {
  if (command === 'logout') {
    userStore.logout()
  } else if (command === 'profile') {
    router.push('/user-center')
  } else if (command === 'settings') {
    ElMessage.info('系统设置功能待开发')
  }
}

// 监听路由变化，确保用户信息已加载
watch(
  () => route.path,
  () => {
    initUserInfo()
  },
)

onMounted(() => {
  initUserInfo()
})
</script>

<template>
  <!-- 登录/注册页不显示应用布局 -->
  <div v-if="isAuthPage">
    <RouterView />
  </div>

  <!-- 应用主布局 -->
  <el-container v-else class="layout-container">
    <!-- 顶部导航栏 -->
    <el-header class="main-header">
      <div class="logo">
        <h1>健康管理系统</h1>
      </div>
      <div class="nav-menu">
        <el-menu
          mode="horizontal"
          :router="true"
          :default-active="route.path"
          background-color="#409eff"
          text-color="#fff"
          active-text-color="#ffd04b"
        >
          <el-menu-item index="/">首页</el-menu-item>
          <el-menu-item
            v-if="userInfo?.role === '超级管理员' || userInfo?.role === '管理员'"
            index="/user-manager"
            >用户管理</el-menu-item
          >
          <el-menu-item v-if="userInfo?.role === '教师'" index="/student-manage"
            >学生管理</el-menu-item
          >
          <el-menu-item index="/injury-report">伤病报告管理</el-menu-item>
          <el-menu-item index="/offline-evaluation">线下评估管理</el-menu-item>
          <el-menu-item index="/online-evaluation">线上评估管理</el-menu-item>
          <el-menu-item
            v-if="userInfo?.role === '超级管理员' || userInfo?.role === '管理员'"
            index="/system-management"
            >系统管理</el-menu-item
          >
          <el-menu-item
            v-if="userInfo?.role === '超级管理员' || userInfo?.role === '管理员'"
            index="/feedback"
            >用户反馈</el-menu-item
          >
        </el-menu>
      </div>
      <div class="user-info">
        <el-dropdown trigger="click" @command="(command: string) => handleCommand(command)">
          <div class="avatar-wrapper">
            <el-avatar :size="40" :src="userInfo?.avatar">{{
              userInfo?.username?.charAt(0)
            }}</el-avatar>
            <span class="user-name">{{ userInfo?.username }}</span>
            <span class="user-role">({{ roleMap[userInfo?.role] || userInfo?.role }})</span>
            <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">个人中心</el-dropdown-item>
              <el-dropdown-item command="settings">系统设置</el-dropdown-item>
              <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <!-- 主内容区 -->
    <el-main class="main-content">
      <RouterView />
    </el-main>

    <!-- 页脚 -->
    <el-footer class="main-footer">
      &copy; {{ new Date().getFullYear() }} 健康管理系统 | 运动康复专业实践能力线上教学工具
    </el-footer>
  </el-container>
</template>

<style>
/* 全局样式，确保页面内容占满整个屏幕 */
html,
body,
#app {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  overflow-x: hidden;
}

#app {
  display: flex;
  flex-direction: column;
}
</style>

<style scoped>
.layout-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  width: 100%;
}

.main-header {
  background-color: #409eff;
  color: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
  height: 60px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  width: 100%;
}

.logo h1 {
  margin: 0;
  font-size: 20px;
  font-weight: bold;
  white-space: nowrap;
  padding: 0 20px;
}

.nav-menu {
  flex: 1;
  width: 100%;
}

.user-info {
  display: flex;
  align-items: center;
  padding: 0 20px;
}

.avatar-wrapper {
  cursor: pointer;
  display: flex;
  align-items: center;
}

.user-name {
  margin: 0 10px;
  color: #ffffff;
}

.user-role {
  margin: 0 10px;
  color: #ffffff;
}

.main-content {
  flex: 1;
  padding: 0;
  background-color: #f5f7fa;
  width: 100%;
  overflow-x: hidden;
}

.main-footer {
  padding: 20px;
  text-align: center;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 14px;
  border-top: 1px solid #e6e6e6;
  width: 100%;
}

/* 确保el-menu组件占满宽度 */
:deep(.el-menu--horizontal) {
  width: 100%;
  display: flex;
  border-bottom: none !important;
}

:deep(.el-menu--horizontal > .el-menu-item) {
  height: 60px;
  line-height: 60px;
  border-bottom: none !important;
}

.management-title {
  font-weight: bold;
  background-color: #2c8cf4 !important;
  margin-right: 10px;
  padding: 0 20px;
}

/* 调整main内容区域 */
:deep(.el-main) {
  padding: 0;
}
</style>
